package org.example.config;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.configuration.FluentConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy;

import javax.sql.DataSource;
import java.util.List;

public class MultiModuleFlywayMigrationStrategy implements FlywayMigrationStrategy {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private List<FluentConfiguration> migrations;

    public MultiModuleFlywayMigrationStrategy(List<FluentConfiguration> migrations) {
        this.migrations = migrations;
    }

    public List<FluentConfiguration> getMigrations() {
        return migrations;
    }

    @Override
    public void migrate(Flyway flyway) {
        this.migrations.forEach((configuration) -> {
            DataSource dataSource = configuration.getDataSource();
            Flyway module = configuration.load();
            if (dataSource == null) {
                module = configuration.dataSource(flyway.getConfiguration().getDataSource()).load();
            }

            try {
//                module.clean();
                module.repair();
            } catch (FlywayException ex) {
                String schemaTable = configuration.getTable();
                logger.error("flyway repair exception,table = {}", schemaTable, ex);
            }

            module.migrate();
        });
    }
}
